<?php

namespace Biz\service\wiki;

use Biz\cache\wiki\GoodsHot;
use Biz\cache\wiki\WikiBasicCounter;
use Biz\cache\wiki\WikiFavorite;
use Biz\model\Album\AlbumWikiListModel;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandAccount\BrandAccountShop;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiAbnormalLog;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\model\wiki\WikiContent as mWikiContent;
use Biz\model\wiki\WikiList as mWikiList;
use Biz\module\Classes\wiki\RelateWiki as clsRelateWiki;
use Biz\module\Classes\wiki\Wiki as clsWiki;
use Biz\pockets\excel\DownExcel;
use Biz\scraper\GoodsInfo as scraperGoodsInfo;
use Biz\service\Album\AlbumWikiListService;
use Biz\service\brand\Brand;
use Biz\service\LinkCleaning\TaskCallbackInitWiki;
use Biz\service\Store\StoreBasicService;
use Biz\service\wiki\Wiki as sWiki;
use Biz\tools\Mail;
use Biz\tools\OneBound;
use Biz\tools\RealUrl;
use Doraemon\model\AdmComplian as mAdmComplian;
use Doraemon\model\Article as mArticle;
use Doraemon\model\Blank as mBlank;
use Doraemon\model\Category;
use Doraemon\model\Category as mCategory;
use Doraemon\model\Guide as mGuide;
use Doraemon\model\IdeaBook as mIdeaBook;
use Doraemon\model\Ideabookcollect as mIdeabookcollect;
use Doraemon\model\Member;
use Doraemon\model\Photos;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\TopicActivity as mTopicActivity;
use Doraemon\service\Category as sCategory;
use Doraemon\service\solr\SolrPhoto;
use Doraemon\service\User;
use Doraemon\service\Videos\Videos;
use Doraemon\tools\BlockType;
use Doraemon\tools\FileOSSGoTool;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;


class AdmWiki
{
    const REJECT_MSG_MAP = [
        1 => '主图不符合审核标准',
        2 => '详情页异常',
        3 => '食品类商品',
        4 => '服装类商品',
        5 => '美妆类商品',
        6 => '饰品类商品',
        7 => '虚拟商品',
    ];

    const RELOAD_WIKI_BASE = 'base';//基础信息、标题、价格
    const RELOAD_WIKI_MUST = 'must';//主要信息，包括基础信息、标题、价格、图片
    const RELOAD_WIKI_ALL = 'all';//
    const RELOAD_WIKI_TBK = 'tbk';//淘宝客商品基础信息
    const RELOAD_WIKI_TBK_BASE = 'tbk_base';//淘宝客商品基础信息、标题、价格、不更新图片

    public static function getChildCategory($id = 0)
    {
        return sCategory::getChildCategory($id);
    }

    public static function admSearchPhotoList($condition)
    {
        $list = [];
        $total = 0;
        $i = 1;
        try {
            list($page, $pageSize) = $condition['LIMIT'];
            $page = ($page / $pageSize) + 1;
            unset($condition['LIMIT']);
            $condition['page'] = $page;
            $condition['page_size'] = $pageSize;
            $rs = SolrPhoto::admSearchByCondition($condition);
            $list = isset($rs['rows']) ? $rs['rows'] : [];
            $total = isset($rs['total']) ? $rs['total'] : 0;
            if (!empty($list)) {
                $photos = Photos::getPhotos($list);

                //按照用户和时间排序
                $time = [];
                foreach ($photos as $row) {
                    $uid[] = $row['uid'];
                    $time[] = $row['addtime'];
                }
                array_multisort($uid, SORT_DESC, $time, SORT_DESC, $photos);
                try {
                    $userInfo = $uid > 0 ? User::getusers_baisic_info($uid) : [];
                    $nickMap = empty($userInfo) ? [] : array_column($userInfo, 'nick', 'uid');
                } catch (\Exception $e) {
                    $nickMap = [];
                }
                $temp = [];
                foreach ($photos as $key => $v) {
                    $temp[] = [
                        'id' => $i++,
                        'pic_id' => $v['id'],
                        'nick' => $v['uid'] . PHP_EOL . (isset($nickMap[$v['uid']]) ? $nickMap[$v['uid']] : ""),
                        'remark' => $v['remark'],
                        'cover_img_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $v['pic_org_id'],
                            ImgUrl::IMAGE_SIZE_ORI_NPHONE),
                        'addtime' => date('Y-m-d H:i:s', $v['addtime']),
                    ];
                }
                $list = $temp;
            }
        } catch (\Exception $e) {

        }
        return compact('list', 'total');
    }

    public static function admSearchContentByReason($reason)
    {
        return mWikiContent::selectByWhere(['reason' => $reason], 'wiki_id');
    }

    private static function getShopUid($channel_type, $channel_shop_id)
    {
        if (in_array($channel_type, [RealUrl::URL_TYPE_TAOBAO, RealUrl::URL_TYPE_TMALL])) {
            $channel_type = [RealUrl::URL_TYPE_TAOBAO, RealUrl::URL_TYPE_TMALL];
        }
        $brandAccountId = BrandAccountShop::getOneByWhere([
            'type' => $channel_type,
            'shop_id' => $channel_shop_id,
            'shop_status' => BrandAccountShop::SHOP_STATUS_VALID
        ], 'account_id');
        $shop_uid = $brandAccountId > 0 ? BrandAccountInfo::getOneByWhere([
            'id' => $brandAccountId,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED
        ], 'uid') : 0;
        return $shop_uid > 0 ? $shop_uid : 0;
    }

    /**
     * @desc 后台审核wiki
     * @param $data
     * @param $where
     * @return bool
     */
    public static function admSaveWiki($data, $where)
    {
        //更新brand_uid
        if ($data['brand_id']) {
            $brandMap = self::admBrandFormat([$data['brand_id']]);
            $data['brand_uid'] = isset($brandMap[$data['brand_id']]) ? $brandMap[$data['brand_id']]['uid'] : 0;
        }

        //更新shop_uid
        $wikiInfo = mWiki::getByWhere($where);
        if ($wikiInfo) {
            $data['shop_uid'] = self::getShopUid($wikiInfo['channel_type'], $data['channel_shop_id']);
        }

        //此商品Wiki审核通过（运营完善过信息）
        //商品与图片关联（看图上的标签，评论中贴链接，后台挂过的图片和商品）
        //商品有相关认证账号（品牌或店铺）
        return mWiki::updateData($data, $where);
    }

    /**
     * @desc 后台审核wiki扩展信息
     * @param $data
     * @param $id
     * @return bool
     */
    public static function admSaveWikiContent($data, $id)
    {
        $where = [
            'wiki_id' => $id,
        ];
        return mWikiContent::updateData($data, $where);
    }

    /**
     * @desc 后台获取获取品牌用户uid
     * @param $nick string 昵称
     * @return int
     */
    public static function admSearchUid($nick)
    {
        return User::getUidByNick($nick);
    }

    /**
     * @desc 后台获取获取品牌id
     * @param $uid int 用户uid
     * @return int
     */
    public static function admGetBrandIdByUid($uid)
    {
        return \Biz\model\brand\Brand::getBrandIdByUid($uid);
    }

    /**
     * @desc 后台获取所有品牌
     * @return int
     */
    public static function admGetBrandList()
    {
        $list = Brand::getAllBrand();
        return empty($list) ? [] : array_column($list, 'brand_name', 'id');
    }

    /**
     * @desc 获取子类目id映射名称
     * @param $parentId int 父类目id
     * @return array
     */
    public static function admGetChildCategoryMap($parentId = 0)
    {
        $rs = sCategory::getChildCategory($parentId);
        return empty($rs) ? [] : array_column($rs, 'cate_name', 'id');
    }

    /**
     * @desc 获取子类目id映射名称
     * @param $parentId int 父类目id
     * @return array
     */
    public static function admGetChildCategoryIds($parentId = 0)
    {
        $rs = Category::getChildrenIds($parentId);
        $children = [];
        $newParent = [];
        foreach ($rs as $v) {
            if ($v['deep'] >= 2) {
                $children[] = $v['id'];
            }
            if ($v['deep'] < 4) {
                $newParent[] = $v['id'];
            }
        }
        if (!empty($newParent)) {
            return array_merge($children, self::admGetChildCategoryIds($newParent));
        }
        return $children;
    }

    /**
     * @desc 后台获取分页获取wiki信息
     * @param $adminEmail
     * @param $condition array 搜索条件
     * @return void
     */
    public static function admExportWikiList($adminEmail, $condition)
    {
        $condition['status[!]'] = mWiki::STATUS_DEL;
        if (!isset($condition['ORDER'])) {
            $condition['ORDER'] = [
                'id' => 'DESC'
            ];
        }
        $rs = mWiki::selectByWhere($condition);
        $list = [];
        if ($rs) {

            $basic_ids = array_column($rs, 'basic_id');
            $cache_hots = GoodsHot::getMulti($basic_ids);
            $cache_ids = array_keys($cache_hots);

            foreach ($rs as $v) {
                $categoryDesc = self::admCategoryFormat($v['last_category_id'], '-', '-', 4); //商城类目 （一二三四级
                $categoryArr = explode('-', $categoryDesc);
                //商品热度
                $hot = 0;
                if (in_array($v['basic_id'], $cache_ids)) {
                    $hot = $cache_hots[$v['basic_id']] ?? 0;
                }
                $list[] = [
                    'id' => $v['id'],  //wiki ID
                    'wiki_id' => $v['basic_id'],  //baisic ID
                    'title' => $v['title'], //商品名称
                    'hot' => $hot, //热度
                    'category' => $categoryArr[0] ?? '',
                    'second_category' => $categoryArr[1] ?? '',
                    'third_category' => $categoryArr[2] ?? '',
                    'four_category' => $categoryArr[3] ?? '',
                    'brand' => $v['channel_brand'], //品牌名称及ID
                    'brand_id' => $v['brand_id'], //品牌名称及ID
                    'channel_type' => mWiki::CHANNEL_TYPE_MAP[$v['channel']], //品牌渠道
                    'channel_spu_status' => mWiki::CHANNEL_STATUS_ARR[$v['channel_spu_status']], //第三方状态
                    'status_desc' => mWiki::ADM_STATUS_MAP[$v['status']] ?? '未知状态',//审核状态
                    'addtime' => $v['addtime'],//创建时间
                    'channel_spu_id' => $v['channel_spu_id'],
                ];
            }
        }

        $sheetData = [
            ['cell_title' => '商品ID', 'cell_key' => 'A', 'cell_width' => 15, 'value_key' => 'id'],
            ['cell_title' => 'WIKI ID', 'cell_key' => 'B', 'cell_width' => 25, 'value_key' => 'wiki_id'],
            ['cell_title' => '商品名称', 'cell_key' => 'C', 'cell_width' => 15, 'value_key' => 'title'],
            ['cell_title' => '热度', 'cell_key' => 'D', 'cell_width' => 15, 'value_key' => 'hot'],
            ['cell_title' => '一级类目', 'cell_key' => 'E', 'cell_width' => 15, 'value_key' => 'category'],
            ['cell_title' => '二级类目', 'cell_key' => 'F', 'cell_width' => 15, 'value_key' => 'second_category'],
            ['cell_title' => '三级类目', 'cell_key' => 'G', 'cell_width' => 15, 'value_key' => 'third_category'],
            ['cell_title' => '四级类目', 'cell_key' => 'H', 'cell_width' => 15, 'value_key' => 'four_category'],
            ['cell_title' => '品牌名称', 'cell_key' => 'I', 'cell_width' => 15, 'value_key' => 'brand'],
            ['cell_title' => '品牌ID', 'cell_key' => 'J', 'cell_width' => 25, 'value_key' => 'brand_id'],
            ['cell_title' => '品牌渠道', 'cell_key' => 'K', 'cell_width' => 15, 'value_key' => 'channel_type'],
            ['cell_title' => '第三方状态', 'cell_key' => 'L', 'cell_width' => 15, 'value_key' => 'channel_spu_status'],
            ['cell_title' => '审核状态', 'cell_key' => 'M', 'cell_width' => 15, 'value_key' => 'status_desc'],
            ['cell_title' => '创建时间', 'cell_key' => 'N', 'cell_width' => 15, 'value_key' => 'addtime'],
            ['cell_title' => '第三方商品ID', 'cell_key' => 'O', 'cell_width' => 15, 'value_key' => 'channel_spu_id'],
        ];

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        //设置表头
        foreach ($sheetData as $row) {
            $sheet->setCellValue($row['cell_key'] . '1', $row['cell_title']);
            $sheet->getColumnDimension($row['cell_key'])->setWidth($row['cell_width']);
        }
        //设置表格数据
        $rowNum = 2; // 从第二行开始
        foreach ($list as $info) {
            foreach ($sheetData as $row) {
                $key = $row['value_key'];
                $value = isset($info[$key]) ? $info[$key] : '';
                $sheet->setCellValue($row['cell_key'] . $rowNum, $value);
            }
            $rowNum++;
        }
        $fileName = 'wiki' . date('YmdHis') . '.xlsx';
        if ($adminEmail) {
            $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR;
            $filePath = $path . $fileName;
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save($filePath);
            $fileSize = filesize($filePath);
            if ($fileSize < 5 * 1000 * 1000) {//5M一下直接发邮件
                Mail::send($adminEmail, 'wiki列表', '下载日期:' . date("Y年m月d日 H:i:s"), $filePath);
            } else {
                FileOSSGoTool::$_requestTimeout = 60; //上传超时时间设置长一些
                $ret = FileOSSGoTool::uploadFile(\Doraemon\service\User::DEFAULT_HAOHAOZHU_UID, $path, $fileName);
                $ossPath = $ret['filePath'];
                Mail::send($adminEmail, 'wiki列表', '下载链接:' . 'https://beerus.haohaozhu.me/admin/extend/file/getOssFileUrl?path=' . $ossPath . '&name=' . $fileName);
            }
        } else {
            ob_end_clean();
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');
            exit();
        }
    }

    /**
     * @desc 后台获取分页获取wiki信息
     * @param $condition array 搜索条件
     * @return array
     */
    public static function admWikiList($condition)
    {
        if (!isset($condition['ORDER'])) {
            $condition['ORDER'] = [
                'id' => 'DESC'
            ];
        }
        if(isset($condition['basic_id']) && empty($condition['basic_id'])){
            unset ($condition['basic_id']);
        }
        $rs = mWiki::selectByWhere($condition);
        $list = [];
        if ($rs) {
            $wikiIds = array_column($rs, 'id');
            $basic_ids = array_column($rs, 'basic_id');
            $cache_hots = GoodsHot::getMulti($basic_ids);
            $cache_ids = array_keys($cache_hots);
            $brandIds = array_column($rs, 'brand_id');
            $brandIds = array_unique(array_filter($brandIds));
            $brandInfos = $brandIds ? Brand::getBrandInfoByIds4Goods($brandIds) : [];
            $storeIds = array_column($rs, 'store_id');
            $storeIds = array_unique(array_filter($storeIds));
            $storeInfos = $storeIds ? StoreBasicService::getStoreInfoByIdArr($storeIds) : [];
            $categorys = mCategory::getAllCategorys(mCategory::STATUS_USING, ['id', 'cate_name']);
            $categoryArr = array_column($categorys, null, 'id');
            $styleList = mWikiBasic::select(['style', 'id'], ['id' => $basic_ids]);
            $styleMap = array_column($styleList, 'style', 'id');
            $counters = WikiBasicCounter::getMulti($basic_ids);
            $albumCountMap = AlbumWikiListModel::getCountMapsByWiki(['wiki_id' => $wikiIds, 'status' => AlbumWikiListModel::STATUS_NORMAL, 'GROUP' => 'wiki_id']);
            if ($albumCountMap) {
                $albumCountMap = array_column($albumCountMap, 'cnt', 'wiki_id');
            }
            foreach ($rs as $v) {
                $uid = $v['brand_uid'] > 0 ? $v['brand_uid'] : $v['shop_uid'];
                //查询品牌账号昵称
                try {
                    $userInfo = $uid > 0 ? User::getUser($uid) : [];
                } catch (\Exception $e) {
                    $userInfo = [];
                }
                $brand_nick = isset($userInfo['nick']) ? $userInfo['nick'] : '';
                //商品热度
                if (in_array($v['basic_id'], $cache_ids)) {
                    $hot = $cache_hots[$v['basic_id']] ?? 0;
                }
                $categoryDesc = '';
                $firstCate = '';
                $secondCate = '';
                $thirdCate = '';
                $fourCate = '';
                if (isset($categoryArr[$v['category_id']])) {
                    $categoryDesc .= $categoryArr[$v['category_id']]['cate_name'];
                    $firstCate = $categoryArr[$v['category_id']]['cate_name'];
                }
                if (isset($categoryArr[$v['second_category_id']])) {
                    $categoryDesc .= '/' . $categoryArr[$v['second_category_id']]['cate_name'];
                    $secondCate = $categoryArr[$v['second_category_id']]['cate_name'];
                }
                if (isset($categoryArr[$v['third_category_id']])) {
                    $categoryDesc .= '/' . $categoryArr[$v['third_category_id']]['cate_name'];
                    $thirdCate = $categoryArr[$v['third_category_id']]['cate_name'];
                }
                if (isset($categoryArr[$v['four_category_id']])) {
                    $categoryDesc .= '/' . $categoryArr[$v['four_category_id']]['cate_name'];
                    $fourCate = $categoryArr[$v['four_category_id']]['cate_name'];
                }
                $list[] = [
                    'id' => $v['id'],
                    'basic_id' => $v['basic_id'],
                    'title' => $v['title'],
                    'brand_uid' => $uid,
                    'brand_id' => $v['brand_id'],
                    'store_id' => $v['store_id'],
                    'status' => $v['status'],
                    'status_desc' => isset(mWiki::ADM_STATUS_MAP[$v['status']]) ? mWiki::ADM_STATUS_MAP[$v['status']] : '未知状态',
                    'brand_nick' => $brand_nick,
                    'brand_info' => $brandInfos[$v['brand_id']] ?? [],
                    'store_info' => $storeInfos[$v['store_id']] ?? [],
                    'cover_img' => self::formatImg($v['cover_img']),
                    'channel_brand' => $v['channel_brand'],
                    'channel_shop_id' => $v['channel_shop_id'],
                    'channel_seller_id' => $v['channel_seller_id'],
                    'channel_shop_name' => $v['channel_shop_name'],
                    'channel_spu_status' => $v['channel_spu_status'],
                    'channel_spu_id' => $v['channel_spu_id'],
                    'channel' => $v['channel'],
                    'channel_type' => $v['channel_type'],
                    'url' => RealUrl::formatLink($v['channel_spu_id'], $v['channel_type'], $v['channel_jump_params'],
                        $v['channel_shop_id']),
                    'addtime' => $v['addtime'],
                    'h5_url' => HhzEnv::detectShopDomain() . 'shop/goods-detail/wiki?wiki_id=' . $v['id'] . '&no-pc-redirect=true',
                    'category_id' => $v['category_id'],
                    'second_category_id' => $v['second_category_id'],
                    'third_category_id' => $v['third_category_id'],
                    'four_category_id' => $v['four_category_id'],
                    'first_cate' => $firstCate,
                    'second_cate' => $secondCate,
                    'third_cate' => $thirdCate,
                    'four_cate' => $fourCate,
                    'category_desc' => $categoryDesc,
                    'hot' => $hot,
                    'is_official' => $v['is_official'],
                    'is_default' => $v['is_default'],
                    'relate_num' => $v['relate_num'],
                    'min_price' => $v['min_price'],
                    'max_price' => $v['max_price'],
                    'wiki_basic_style' => $styleMap[$v['basic_id']] ?? '',
                    'fav_count' => $counters[$v['basic_id']][WikiBasicCounter::BASIC_FAVORITE] ?? 0,
                    'album_count' => $albumCountMap[$v['id']] ?? 0,
                ];
            }
        }

        if (isset($condition['LIMIT'])) {
            unset($condition['LIMIT']);
        }
        if (isset($condition['ORDER'])) {
            unset($condition['ORDER']);
        }
        $total = mWiki::count($condition);
        return compact('list', 'total');
    }


    public static function abnormalWikiList($condition)
    {
        $condition['c_type'] = 1;
        $condition['ORDER'] = ['addtime' => 'DESC'];
        $result = mAdmComplian::select('*', $condition);
        unset($condition['ORDER']);
        unset($condition['LIMIT']);
        $total = mAdmComplian::count('*', $condition);
        $uids = array_column($result, 'uid');
        $userList = User::getUsers($uids);
        $list = [];
        foreach ($result as $row) {
            $fromArr = $row['from'] ? explode(':', $row['from']) : [];
            $info = [
                'wiki_id' => $fromArr ? $fromArr[1] : '',
                'uid' => $row['uid'],
                'nick' => isset($userList[$row['uid']]) ? $userList[$row['uid']]['nick'] : '',
                'addtime' => date('Y-m-d H:i:s', $row['addtime']),
                'reason' => mAdmComplian::WIKI_MSG_MAP[$row['type']],
                'desc' => $row['message'],
            ];
            $list[] = $info;
        }
        return compact('list', 'total');
    }

    public static function userShareWikiList($condition)
    {
        $condition['c_type'] = 1;
        $condition['ORDER'] = ['addtime' => 'DESC'];
        $result = mAdmComplian::select('*', $condition);
        unset($condition['ORDER']);
        unset($condition['LIMIT']);
        $total = mAdmComplian::count('*', $condition);
        $uids = array_column($result, 'uid');
        $userList = User::getUsers($uids);
        $list = [];
        foreach ($result as $row) {
            $fromArr = $row['from'] ? explode(':', $row['from']) : [];
            $info = [
                'wiki_id' => $fromArr ? $fromArr[1] : '',
                'uid' => $row['uid'],
                'nick' => isset($userList[$row['uid']]) ? $userList[$row['uid']]['nick'] : '',
                'addtime' => date('Y-m-d H:i:s', $row['addtime']),
                'reason' => mAdmComplian::WIKI_MSG_MAP[$row['type']],
                'desc' => $row['message'],
            ];
            $list[] = $info;
        }
        return compact('list', 'total');
    }

    static $_admCategory = [];

    private static function admCategoryFormat($last_cate_id, $default = '-', $delimiter = '-', $limit = 2)
    {
        if (isset(self::$_admCategory[$last_cate_id])) {
            return self::$_admCategory[$last_cate_id];
        }
        $cateList = [];
        if ($last_cate_id > 0) {
            $cateList = Category::getTreeArrById($last_cate_id);
            $cateList = array_column($cateList, 'cate_name');
            $cateList = array_slice($cateList, 0, $limit);
        }
        return self::$_admCategory[$last_cate_id] = empty($cateList) ? $default : implode($delimiter, $cateList);
    }

    public static function admBrandFormat($brand_ids)
    {
        $list = \Biz\model\brand\Brand::getInfoByIds($brand_ids);
        $response = empty($list) ? [] : array_column($list, null, 'id');
        return $response;
    }


    /**
     * @desc 后台获取wiki信息
     * @param $id
     * @return array
     */
    public static function getInfoById($id)
    {
        $response = [];
        if ($id > 0) {
            $info = mWiki::getByWhere(['id' => $id]);
            $basicInfo = mWikiBasic::getInfosByBasicIds([$info['basic_id']]);
            $styleStr = $basicInfo[$info['basic_id']]['style'] ?? '';
            if (empty($styleStr)) {
                $styleList = AdmWikiTag::getStyleList();
                $style = AdmWikiTag::matchWikiTags($styleList, $info['title']);
                if ($info['tags']) {
                    $wikiTags = AdmWikiTag::formatStyle($info['tags']);//第三方标签 参考
                    $style = array_merge($style, AdmWikiTag::matchWikiTags($styleList, $wikiTags));
                }
                $info['wiki_basic_style_match'] = true; //系统自动匹配了标签
            } else {
                $style = explode(',', $styleStr);
                $info['wiki_basic_style_match'] = false;
            }
            $ext = mWikiContent::getByWhere(['wiki_id' => $id]);
            $content = self::formatContent($ext['content'] ?? '');
            $info['imgs'] = $ext['imgs'] ?? '';
            $info['content_text'] = $content['style'] . $content['text'];
            $info['content_style'] = $content['style'];
            $info['reason'] = $ext['reason'] ?? '';
            $info['detail_imgs'] = $ext['detail_imgs'] ?? '';
            $info['wiki_basic_style'] = $style;
            if ($info) {
                $response = self::format($info);
            }
        }
        return $response;
    }

    public static function formatContent($content)
    {
        $pattern = '/<style>([\s\S]*?)<\/style>/';
        preg_match_all($pattern, $content, $matches);
        $styles = [];
        if ($matches) {
            $styles = $matches[0];
        }
        $text = preg_replace($pattern, "", $content);
        $style = implode("", $styles);
        return compact('text', 'style');
    }

    public static function format($info)
    {
        if (isset($info['channel']) && isset($info['channel_spu_id'])) {
            $info['url'] = RealUrl::formatLink($info['channel_spu_id'], $info['channel_type'],
                $info['channel_jump_params'], $info['channel_shop_id']);
        }
        if (isset($info['channel'])) {
            $info['channel'] = isset(mWiki::CHANNEL_MAP[$info['channel']]) ? mWiki::CHANNEL_MAP[$info['channel']] : '未知渠道';
        }
        if (isset($info['min_price']) && isset($info['max_price'])) {
            $info['price'] = implode('~', [$info['min_price'], $info['max_price']]);
        }
        if (isset($info['last_category_id'])) {
            $cateList = Category::getTreeArrById($info['last_category_id']);
            $cateList = array_column($cateList, 'id');
            $info['category_id'] = isset($cateList[0]) ? $cateList[0] : 0;
            $info['second_category_id'] = isset($cateList[1]) ? $cateList[1] : 0;
            $info['third_category_id'] = isset($cateList[2]) ? $cateList[2] : 0;
            $info['four_category_id'] = isset($cateList[3]) ? $cateList[3] : 0;
        }
        if (isset($info['cover_img'])) {
            $info['cover_img_url'] = self::formatImg($info['cover_img']);
        }
        if (isset($info['imgs'])) {
            $sourceFiles = $info['imgs'] ? json_decode($info['imgs'], true) : [];
            $sourceFiles = is_array($sourceFiles) ? $sourceFiles : [];
            $dataFiles = array_map(function ($v) {
                return self::formatImg($v);
            }, $sourceFiles);
            $sourceFiles = implode(',', $sourceFiles);
            $dataFiles = implode(',', $dataFiles);
            $info['sourceFiles'] = $sourceFiles;
            $info['dataFiles'] = $dataFiles;
        }

        //关联点图标签id
        if (isset($info['id'])) {
            $relateList = mObjRelateWiki::getByWhere([
                'AND' => [
                    'obj_type' => [mObjRelateWiki::OBJ_TYPE_NOTE, mObjRelateWiki::OBJ_TYPE_BLANK],
                    'wiki_id' => $info['id']
                ],
                'ORDER' => ['addtime' => 'DESC']
            ], ['obj_id', 'obj_type']);
            $relateNoteIds = [];
            $relateBlankIds = [];
            foreach ($relateList as $row) {
                if ($row['obj_type'] == mObjRelateWiki::OBJ_TYPE_NOTE) {
                    $relateNoteIds[] = $row['obj_id'];
                }
                if ($row['obj_type'] == mObjRelateWiki::OBJ_TYPE_BLANK) {
                    $relateBlankIds[] = $row['obj_id'];
                }
            }
            $info['relate_note_id'] = !empty($relateNoteIds) ? implode(',', array_unique($relateNoteIds)) : "";
            $info['relate_blank_id'] = !empty($relateBlankIds) ? implode(',', array_unique($relateBlankIds)) : "";
        }

        return $info;
    }

    public static function formatImg($pic_id)
    {
        $pattern = '/(http|https):\/\/([\w.]+\/?)\S*/';
        if (preg_match($pattern, $pic_id) || strpos($pic_id, '//') == 0) {
            $url = $pic_id;
        } else {
            $url = $pic_id ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $pic_id, ImgUrl::IMAGE_SIZE_OP_ORI) : '';
        }
        return $url;
    }

    /**
     * @param $params
     * @return bool
     */
    public static function scraperReloadData($args)
    {
        $params = $args['params'];
        $id = $params['id'];
        $reloadField = isset($params['reload_field']) ? $params['reload_field'] : self::RELOAD_WIKI_ALL;
        if (!$id) {
            Log::debug('参数错误', $args);
        } else {
            $info = mWiki::getByWhere(['id' => $id]);
            if ($info) {
                $wikiInfo = self::admReloadWiki($info, $reloadField);
                if ($wikiInfo) {
                    Log::info('重新抓取商品信息成功,wiki_id:' . $id);
                } else {
                    Log::debug('重新抓取商品信息失败,wiki_id:' . $id, $args);
                }
            } else {
                Log::debug('参数不到的wiki信息,wiki_id:' . $id, $args);
            }
        }
    }

    /**
     * @param $params
     * @return bool
     */
    public static function scraperUpdateByOneBound($args)
    {
        $params = $args['params'];
        $id = $params['id'];
        if (!$id) {
            Log::debug('#OneBound#参数错误', $args);
        } else {
            $info = mWiki::getByWhere(['id' => $id]);
            if ($info) {
                clsWiki::updateByOneBound($info);
                Log::info('#OneBound#调用万邦更新商品信息成功,wiki_id:' . $id);
            } else {
                Log::debug('#OneBound#不存在的wiki信息,wiki_id:' . $id, $args);
            }
        }
    }

    private static function compareUnionInfo($wikiInfo, $unionInfo, $reloadField)
    {
        $reloadFields = ['title', 'cover_img', 'min_price', 'max_price'];
        switch ($reloadField) {
            case self::RELOAD_WIKI_BASE:
            case self::RELOAD_WIKI_TBK_BASE:
                $reloadFields = ['title', 'min_price', 'max_price'];
                break;
            case self::RELOAD_WIKI_MUST:
                $reloadFields = ['title', 'cover_img', 'min_price', 'max_price'];
                break;
        }
        $isReload = false;
        if (empty($unionInfo)) {
            return true;
        }
        foreach ($wikiInfo as $key => $val) {
            if (!$isReload && in_array($key, $reloadFields)) {
                switch ($key) {
                    case 'title':
                        if ($unionInfo[$key] && $unionInfo[$key] != $val) {
                            $isReload = true;
                        }
                        break;
                    case 'cover_img':
                        if ($unionInfo[$key]) {
                            $unionParseArr = parse_url($unionInfo[$key]);
                            $unionParseUrl = 'https://' . $unionParseArr['host'] . $unionParseArr['path'];

                            $infoParseUrl = parse_url($val);
                            $coverImgUrl = 'https://' . $infoParseUrl['host'] . $infoParseUrl['path'];

                            if ($unionParseUrl != $coverImgUrl) {
                                $isReload = true;
                            }
                        }
                        break;
                    case 'min_price':
                    case 'max_price':
                        if (isset($scraperWikiInfo[$key]) && bccomp($scraperWikiInfo[$key], $val, 2) != 0) {
                            $isReload = true;
                        }
                        break;
                }
            }
        }
        return $isReload;
    }

    /**
     * 重新抓取商品
     * @param $info
     * @param bool $reloadField 需要抓取的信息（all：默认全部； base：基础信息、标题、价格，must：必要信息，基础和图片信息）
     * @return array|false|mixed
     * @throws \Exception
     */
    public static function admReloadWiki($info, $reloadField = self::RELOAD_WIKI_ALL)
    {
        $addTask = false;
        $wikiInfo = [];
        $url = !empty($info) ? RealUrl::formatLink($info['channel_spu_id'], $info['channel_type'],
            $info['channel_jump_params'], $info['channel_shop_id']) : '';
        if (empty($url)) {
            throw new \Exception('获取链接失败');
        }
        if (in_array($reloadField, [self::RELOAD_WIKI_TBK, self::RELOAD_WIKI_TBK_BASE]) && $info['channel'] != mWiki::CHANNEL_TAOBAO) {
            return;
        }
        $unionInfoArr = scraperGoodsInfo::getUnionInfo($url);
        if ($unionInfoArr) {
            $unionInfo = $unionInfoArr['union_info'];
            $channelInfo = $unionInfoArr['channel_info'];
            $itemId = $channelInfo['channel_spu_id'];
            $channelType = $channelInfo['channel_type'];
            $isAllReload = ($reloadField == self::RELOAD_WIKI_ALL) ? true : false;
            if (!$isAllReload) {
                $isReload = self::compareUnionInfo($info, $unionInfo, $reloadField);
                if (!$isReload) {//如果没有需要更新的数据
                    Log::info('没有要更新的数据#wiki_id:' . $info['id']);
                    $isAbnormal = (isset($unionInfo['channel_spu_status']) && $unionInfo['channel_spu_status'] == 0) ? true : false;
                    //记录重新抓取失败的wiki
                    WikiAbnormalLog::updateAbnormalCount($info['id'], $isAbnormal);
                    return $info;
                }
            }
            $scraperWikiInfo = $unionInfo;
            if (!in_array($reloadField, [self::RELOAD_WIKI_TBK, self::RELOAD_WIKI_TBK_BASE])) {
                /*
                $useDingDanXia = scraperGoodsInfo::useDingDanXia($unionInfo);
                $dingDanXiaGoodsInfo = [];
                if ($useDingDanXia) {
                    if ($unionInfo) {
                        $dingDanXiaGoodsInfo = DingDanXia::getTbkItemInfo($channelType, $itemId);
                    } else {
                        $dingDanXiaGoodsInfo = scraperGoodsInfo::getDingDanXiaInfo($itemId, $channelType, $isAllReload);
                    }
                }
                $scraperWikiInfo = scraperGoodsInfo::formatDingDanXiaGoodsInfo($unionInfo, $dingDanXiaGoodsInfo);
                */
                $oneBoundInfo = OneBound::getTaoBaoItemInfo($itemId, $channelType);
                $scraperWikiInfo = scraperGoodsInfo::formatOneBoundInfo($scraperWikiInfo, $oneBoundInfo);
            }
            if ($scraperWikiInfo) {
                $channel = clsWiki::getChannel($channelType);
                if (!$channel) {
                    throw new \Exception('抓取链接获取的channel不正确#channel_type:' . $scraperWikiInfo['channel_type'] . '#channel:' . $channel);
                    return false;
                }
                $scraperWikiInfo['channel'] = $channel;
                $wikiInfo = mWiki::getInfoByChannelSpu($scraperWikiInfo['channel'], $scraperWikiInfo['channel_spu_id']);
                $wikiData = [];
                $wikiContentData = [];
                if (!empty($wikiInfo)) {
                    $wikiContentInfo = mWikiContent::getByWikiId($wikiInfo['id']);
                    $changeKey = [
                        "title",
                        "channel_brand",
                        "channel_seller_id",
                        "channel_shop_id",
                        "channel_shop_name",
                        "channel_category_name",
                        "cover_img",
                        "min_price",
                        "max_price",
                        "channel_jump_params",
                        "tags",
                        "channel_spu_status"
                    ];
                    foreach ($scraperWikiInfo as $key => $val) {
                        if (in_array($key, $changeKey)) {
                            if (in_array($key, ['min_price', 'max_price']) && (int)$val >= 0) {
                                $wikiData[$key] = $val;
                                $wikiInfo[$key] = $val;
                            } else {
                                if ($key == 'channel_spu_status') {
                                    $wikiData[$key] = $val;
                                    $wikiInfo[$key] = $val;
                                } else if ($key == 'tags') {
                                    $valTags = json_decode($val, true);
                                    $valMaterial = isset($valTags['material']) ? $valTags['material'] : [];
                                    $valStyle = isset($valTags['style']) ? $valTags['style'] : [];

                                    $wikiTags = !empty($wikiInfo['tags']) ? json_decode($wikiInfo['tags'], true) : [];
                                    $wikiMaterial = isset($wikiTags['material']) ? $wikiTags['material'] : [];
                                    $wikiStyle = isset($wikiTags['style']) ? $wikiTags['style'] : [];

                                    $material = array_unique(array_filter(array_merge($valMaterial, $wikiMaterial)));
                                    $style = array_unique(array_filter(array_merge($valStyle, $wikiStyle)));
                                    $tags = [];
                                    if ($style) {
                                        $tags['style'] = array_values($style);
                                    }
                                    if ($material) {
                                        $tags['material'] = array_values($material);
                                    }
                                    $wikiData[$key] = $tags ? json_encode($tags, JSON_UNESCAPED_UNICODE) : '';
                                    $wikiInfo[$key] = $tags ? json_encode($tags, JSON_UNESCAPED_UNICODE) : '';
                                } else {
                                    if (!empty($val)) {
                                        $wikiData[$key] = $val;
                                        $wikiInfo[$key] = $val;
                                    }
                                }
                            }
                        }
                    }
                    if (isset($scraperWikiInfo['imgs']) && $scraperWikiInfo['imgs'] && $reloadField != self::RELOAD_WIKI_BASE) {
                        $wikiContentData['imgs'] = $scraperWikiInfo['imgs'];
                    }
                    if (isset($scraperWikiInfo['content']) && $scraperWikiInfo['content'] && $reloadField != self::RELOAD_WIKI_BASE) {
                        $wikiContentData['content'] = $scraperWikiInfo['content'];
                    }
                    if (!$scraperWikiInfo['title'] || !$scraperWikiInfo['cover_img']
                        || !$scraperWikiInfo['channel_shop_id'] || !$scraperWikiInfo['channel_shop_name']
                        || $scraperWikiInfo['min_price'] <= 0 || $scraperWikiInfo['max_price'] <= 0
                        || !$scraperWikiInfo['imgs'] || !$scraperWikiInfo['content']) {
                        //添加抓取wiki任务
                        $addTask = true;
                    }
                    if (in_array($wikiInfo['status'], [mWiki::STATUS_NORMAL, mWiki::STATUS_DEL])) {
                        if ($wikiInfo['title'] && $wikiInfo['cover_img']
                            && ($wikiInfo['channel_shop_id'] || $wikiInfo['channel_seller_id'])
                            && $wikiInfo['min_price'] > 0 && $wikiInfo['max_price'] > 0
                            && $wikiContentData['imgs'] && $wikiContentData['content']
                        ) {
                            $wikiData['status'] = mWiki::STATUS_WAIT_CHECK;
                        }
                    }
                    if (!$scraperWikiInfo['channel_shop_name'] && !$wikiInfo['channel_shop_name']) {
                        $addTask = true;
                    }
                    if ($wikiData) {
                        if (in_array($reloadField, [self::RELOAD_WIKI_BASE, self::RELOAD_WIKI_TBK_BASE])) {
                            unset($wikiData['cover_img']);
                        }
                        mWiki::updateData($wikiData, ['id' => $wikiInfo['id']]);
                    }
                    if ($wikiContentData) {
                        if (!$wikiContentInfo) {
                            $wikiContentData['wiki_id'] = $wikiInfo['id'];
                            mWikiContent::insertData($wikiContentData);
                        } else {
                            mWikiContent::updateData($wikiContentData, ['wiki_id' => $wikiInfo['id']]);
                        }
                    }
                    if ($wikiInfo['basic_id']) {
                        $wikiBasicInfo = mWikiBasic::getByWhere(['id' => $wikiInfo['basic_id']]);
                        if ($wikiBasicInfo && $wikiBasicInfo['brand_id'] == 0 && !empty($wikiData['title'])) {
                            mWikiBasic::updateData(['title' => $wikiData['title']], ['id' => $wikiInfo['basic_id']]);
                        }
                    }
                }
            }
        }
        if ($wikiInfo) {
            $isAbnormal = (isset($scraperWikiInfo['channel_spu_status']) && $scraperWikiInfo['channel_spu_status'] == 0) ? true : false;
            //记录重新抓取失败的wiki
            WikiAbnormalLog::updateAbnormalCount($info['id'], $isAbnormal);
            $id = $wikiInfo['id'];
            if ($isAllReload && $addTask && $id && !in_array($channel,
                    [mWiki::CHANNEL_TYPE_YOUZAN, mWiki::CHANNEL_NOTHING])) {//有赞不支持 网多云抓取
                if ($channel == mWiki::CHANNEL_TAOBAO) {
                    scraperGoodsInfo::addOneBoundTask($id);
                } else {
                    scraperGoodsInfo::addTaskCopy($url, [AdmWiki::class, 'afterCleaningDataRecoverWiki'], compact('id'));
                }
            }
        } else {
            if (isset($unionInfoArr['channel_info']) && $unionInfoArr['channel_info']) {
                $channelType = $unionInfoArr['channel_info']['channel_type'];
                $channelSpuId = $unionInfoArr['channel_info']['channel_spu_id'];
                $channel = clsWiki::getChannel($channelType);
                if (!in_array($channel, [mWiki::CHANNEL_TYPE_YOUZAN, mWiki::CHANNEL_NOTHING])) {
                    $sign = [
                        'obj_type' => 1,
                        'obj_id' => null
                    ];
                    $url = RealUrl::formatLink($channelSpuId, $channelType);
                    scraperGoodsInfo::addTask($sign, $url, TaskCallbackInitWiki::class);
                }
            }
            //记录重新抓取失败的wiki
            WikiAbnormalLog::updateAbnormalCount($info['id'], true);
            Log::debug('查询不到第三方商品信息,wiki_id:' . $info['id']);
            throw new \Exception('不存在的商品');
        }
        return $wikiInfo;
    }

    /**
     * 清洗完的数据覆盖wiki
     * @param $params array 清洗的数据
     * @return bool
     */
    public static function afterCleaningDataRecoverWiki($params)
    {
        try {
            $cleaningData = isset($params['cleanData']) ? $params['cleanData'] : [];
            $wikiId = isset($params['id']) ? $params['id'] : 0;
            if (empty($cleaningData) || ($wikiId <= 0)) {
                throw new \Exception('参数错误');
            }
            $channelType = $cleaningData['type'];

            $channel_spu_id = $cleaningData['goods_id'] ?? 0;
            $channel_shop_id = $cleaningData['shop_id'] ?? 0;
            $channel_shop_name = $cleaningData['shop_name'] ?? '';
            // 感觉这样不太准确
//            if (!$channel_shop_name) {
//                //查询淘宝客的店铺名称
//                $rs = \Biz\tools\Tbk::getItemInfo($channel_spu_id);
//                $nick = $rs['nick'] ?? '';
//                if (strlen($nick)) $channel_shop_name = $nick;
//
//                //使用店铺名称匹配店铺id
//                if ($channel_shop_id == 0) {
//                    $shop_id = BrandShop::getOneByWhere('shop_id', ['name' => $channel_shop_name, 'status' => 1]);
//                    if ($shop_id != 0) $channel_shop_id = $shop_id;
//                }
//            }

            $wikiData = [
                'title' => $cleaningData['name'],
                'channel' => $cleaningData['channel'],
                'channel_type' => $channelType,
                'channel_brand' => $cleaningData['brand'],
                'channel_shop_id' => $channel_shop_id,
                'channel_shop_name' => $channel_shop_name,
                'channel_spu_id' => $channel_spu_id,
                'channel_category_name' => $cleaningData['category'],
                'cover_img' => isset($cleaningData['images'][0]) ? $cleaningData['images'][0] : '',
                'min_price' => $cleaningData['min_price'],
                'max_price' => $cleaningData['max_price'],
                'status' => mWiki::STATUS_WAIT_CHECK,
                'category_id' => $cleaningData['one_category_id'],
                'second_category_id' => $cleaningData['two_category_id'],
                'last_category_id' => $cleaningData['last_category_id'],
                'shop_uid' => $channel_shop_id > 0 ? self::getShopUid($channelType, $channel_shop_id) : 0,

            ];
            $wikiInfo = mWiki::getByWhere(['id' => $wikiId]);
            $changeKey = ["category_id", "second_category_id", "last_category_id"];
            foreach ($wikiInfo as $key => $val) {
                if (in_array($key, $changeKey)) {
                    if ($val) {
                        unset($wikiData[$key]);
                    }
                }
            }
            $contentData = [
                'imgs' => isset($cleaningData['images']) ? json_encode($cleaningData['images'], true) : '',
                'content' => $cleaningData['detail'],
            ];
            //覆盖wiki信息
            mWiki::updateData($wikiData, ['id' => $wikiId]);
            $contentInfo = mWikiContent::getByWhere(['wiki_id' => $wikiId]);
            if ($contentInfo) {
                if ($contentInfo['imgs']) {
                    unset($contentData['imgs']);
                }
                if ($contentInfo['content']) {
                    unset($contentData['content']);
                }
                if ($contentData) {
                    mWikiContent::updateData($contentData, ['wiki_id' => $wikiId]);
                }
            } else {
                $contentData['wiki_id'] = $wikiId;
                mWikiContent::insertData($contentData);
            }
            Log::info('清洗完的数据覆盖wiki', compact('params'));
            return true;
        } catch (\Exception $e) {
            $trace = [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'msg' => $e->getMessage(),
            ];
            Log::info('清洗完的数据覆盖wiki', compact('params', 'trace'));
            return false;
        }
    }

    /**
     * @param string $name 灵感集名称
     * @param int $uid 用户ID
     * @return array
     */
    public static function admGetPicByIdeaBookName($name = '', $uid = 0)
    {
        $pics = [];
        $ideaBooks = [];
        if (strlen($name) > 0) {
            $condition = $uid > 0 ? ['name' => $name, 'uid' => $uid] : ['name' => $name];
            $condition['status'] = mIdeaBook::STATUS_NORMAL;
            $ideaBooks = mIdeaBook::select("*", $condition);
        }

        if (!empty($ideaBooks)) {
            foreach ($ideaBooks as $ideaBook) {
                $tempPics = mIdeabookcollect::select("photo_id", [
                    "AND" => [
                        "uid" => $ideaBook['uid'],
                        "idea_book_id" => $ideaBook['id'],
                        "status" => mIdeabookcollect::STATUS_NORMAL,
                    ],
                ]);
                if ($tempPics) {
                    $pics = array_merge($pics, $tempPics);
                }
            }
        }
        return $pics;
    }

    /**
     * @param int $idea_book_id 灵感集ID
     * @return array
     */
    public static function admGetPicByIdeaBook($idea_book_id = 0)
    {
        $pics = [];
        $ideaBook = [];
        if ($idea_book_id > 0) {
            $ideaBook = mIdeaBook::getIdeaBookById($idea_book_id);
        }
        if (!empty($ideaBook)) {
            $pics = mIdeabookcollect::select("photo_id", [
                "AND" => [
                    "uid" => $ideaBook['uid'],
                    "idea_book_id" => $ideaBook['id'],
                    "status" => mIdeabookcollect::STATUS_NORMAL,
                ],
            ]);
        }
        return $pics;
    }

    public static function admGetTopicIdByName($name)
    {
        $ids = mTopicActivity::select('id', ['title[~]' => $name]);
        return empty($ids) ? [] : $ids;
    }

    public static function admGetArticleIdByName($name)
    {
        $ids = mArticle::select('aid', ['title[~]' => $name]);
        return empty($ids) ? [] : $ids;
    }

    /**
     * 下架wiki
     * @param $wikiId
     * @param $adminUid
     * @return bool
     */
    public static function admOfflineWiki($wikiId, $adminUid)
    {
        $relateList = mObjRelateWiki::getByWhere(['wiki_id' => $wikiId]);
        mWiki::updateData(['status' => mWiki::STATUS_DEL], ['id' => $wikiId]);
        mObjRelateWiki::updateData(['status' => mObjRelateWiki::STATUS_DEL], ['wiki_id' => $wikiId]);
        mWikiContent::updateData(['operator' => $adminUid], ['wiki_id' => $wikiId]);
        foreach ($relateList as $row) {
            $uid = $row['uid'];
            $wikiId = $row['wiki_id'];
            $objId = $row['obj_id'];
            $objType = $row['obj_type'];
            clsRelateWiki::afterRelateWiki($uid, [$wikiId], $objId, $objType);
        }
        $info = mWiki::getByWhere(['id' => $wikiId]);
        if ($info['basic_id']) {
            WikiBasic::afterChangeBasic([$info['basic_id']], $info['brand_id']);
        }
        AlbumWikiListService::afterOffLineWiki($wikiId);
        return true;
    }

    /**
     * 根据commentId获取wiki及url
     * @param array $commentsArr [['obj_id'=>'000d7xt00000xx6f','rel_obj_id'=>1],['obj_id'=>'000d7xt00000xx6f','rel_obj_id'=>2]...]
     * @return array
     */
    public static function admGetWikiUrlByCommentId(array $commentsArr)
    {
        $result = [];
        if ($commentsArr) {
            $commentsKeyList = [];
            $commentIds = [];
            foreach ($commentsArr as $row) {
                $commentsKeyList[] = $row['obj_id'] . '_' . $row['rel_obj_id'];
                $commentIds[] = $row['rel_obj_id'];
            }
            $commentIds = array_unique($commentIds);
            $where = [
                'rel_obj_type' => mObjRelateWiki::REL_OBJ_TYPE_COMMENT,
                'rel_obj_id' => $commentIds,
                'status' => mObjRelateWiki::STATUS_NORMAL,
                'wiki_id[!]' => 0,
            ];
            $list = mObjRelateWiki::getByWhere($where,
                ['obj_id', 'obj_type', 'rel_obj_id', 'rel_obj_type', 'wiki_id', 'status']);
            $wikiIds = array_column($list, 'wiki_id');
            $wikiIds = array_unique($wikiIds);
            $wikiList = mWiki::getInfosByWikiIds($wikiIds,
                ['id', 'status', 'channel_type', 'channel_spu_id', 'channel_jump_params', 'channel_shop_id']);
            foreach ($list as $row) {
                $wikiId = $row['wiki_id'];
                $commentKey = $row['obj_id'] . '_' . $row['rel_obj_id'];
                if (isset($wikiList[$wikiId]) && in_array($commentKey, $commentsKeyList)) {
                    $result[$commentKey] = [
                        'wiki_id' => $wikiId,
                        'url' => RealUrl::formatLink($wikiList[$wikiId]['channel_spu_id'],
                            $wikiList[$wikiId]['channel_type'], $wikiList[$wikiId]['channel_jump_params'],
                            $wikiList[$wikiId]['channel_shop_id'])
                    ];
                }
            }
        }
        return $result;
    }

    /**
     * @desc 后台获取分页获取wiki信息
     * @param $condition array 搜索条件
     * @return array
     */
    public static function admShareWikiList($condition)
    {
        if (!isset($condition['ORDER'])) {
            $condition['ORDER'] = [
                'id' => 'DESC'
            ];
        }
        if ($condition['uid']) {
            $wikiIdsList = mWikiList::selectByWhere(['uid' => $condition['uid']]);
            if ($wikiIdsList) {
                $wikiIds = array_column($wikiIdsList, 'wiki_id');
                unset($condition['uid']);
                $condition['id'] = $wikiIds;
            }
        }
        $rs = mWiki::selectByWhere($condition);
        $wikiIds = array_column($rs, 'id');
        $favCounterList = WikiFavorite::getCounter($wikiIds);
        $list = [];
        if ($rs) {
            foreach ($rs as $v) {
                $uid = $v['brand_uid'] > 0 ? $v['brand_uid'] : $v['shop_uid'];
                //查询品牌账号昵称
                try {
                    $userInfo = $uid > 0 ? User::getUser($uid) : [];
                } catch (\Exception $e) {
                    $userInfo = [];
                }
                $brand_nick = isset($userInfo['nick']) ? $userInfo['nick'] : '';
                $v['fav_count'] = isset($favCounterList[$v['id']]) ? $favCounterList[$v['id']] : 0;
                $shareTableResult = self::getShareUsersTable($v['id']);
                $shareTable = $shareTableResult['table'];
                $shareCount = $shareTableResult['count'];
                $list[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'brand_uid' => $uid,
                    'status' => $v['status'],
                    'status_desc' => isset(mWiki::ADM_STATUS_MAP[$v['status']]) ? mWiki::ADM_STATUS_MAP[$v['status']] : '未知状态',
                    'brand_nick' => $brand_nick,
                    'cover_img' => self::formatImg($v['cover_img']),
                    'channel_brand' => $v['channel_brand'],
                    'channel_shop_name' => $v['channel_shop_name'],
                    'url' => RealUrl::formatLink($v['channel_spu_id'], $v['channel_type'], $v['channel_jump_params'],
                        $v['channel_shop_id']),
                    'addtime' => $v['addtime'],
                    'h5_url' => HhzEnv::detectShopDomain() . 'shop/goods-detail/wiki?wiki_id=' . $v['id'] . '&no-pc-redirect=true',
                    'category_desc' => self::admCategoryFormat($v['last_category_id']),
                    'designer_share' => $v['designer_share'],
                    'recommendation' => swiki::getWikiRecommendation($v),
                    'share_table' => $shareTable,
                    'share_count' => $shareCount
                ];
            }
        }

        if (isset($condition['LIMIT'])) {
            unset($condition['LIMIT']);
        }
        if (isset($condition['ORDER'])) {
            unset($condition['ORDER']);
        }
        $total = mWiki::count($condition);
        return compact('list', 'total');
    }

    public static function getShareUsersTable($wikiId)
    {
        $relateList = mObjRelateWiki::select('*', ['wiki_id' => $wikiId, 'status' => mObjRelateWiki::STATUS_NORMAL]);
        $uids = $relateList ? array_column($relateList, 'uid') : [];
        $uids = array_unique($uids);
        $count = count($uids);
        $userList = User::getBatchBasicUserInfo($uids);
        $userList = $userList ? array_column($userList, null, 'uid') : [];
        $objList = [];
        $noteIds = [];
        $blankIds = [];
        $articleIds = [];
        $guideIds = [];
        foreach ($relateList as $row) {
            if (!isset($objList[$row['obj_type']])) {
                $objList[$row['obj_type']] = [];
            }
            if (!in_array($row['obj_id'], $objList[$row['obj_type']])) {
                switch ($row['obj_type']) {
                    case mObjRelateWiki::OBJ_TYPE_NOTE:
                        $noteIds[] = $row['obj_id'];
                        break;
                    case mObjRelateWiki::OBJ_TYPE_BLANK:
                        $blankIds[] = $row['obj_id'];
                        break;
                    case mObjRelateWiki::OBJ_TYPE_ARTICLE:
                        $articleIds[] = $row['obj_id'];
                        break;
                    case mObjRelateWiki::OBJ_TYPE_GUIDE:
                        $guideIds[] = $row['obj_id'];
                        break;
                }
                $objList[$row['obj_type']][] = $row['obj_id'];
            }
        }

        $noteInfos = $noteIds ? mPhotos::getPhotos($noteIds) : [];
        $video_ids = array_filter(array_unique(array_column($noteInfos, 'video_id')));
        $videos = Videos::getCanUseVideoInfosByIds($video_ids);
        $articleInfos = $articleIds ? mArticle::getArticles($articleIds) : [];
        $articleInfos = $articleInfos ? array_column($articleInfos, null, 'aid') : [];
        $blankInfos = $blankIds ? mBlank::getBatchBlankByIds($blankIds) : [];
        $blankInfos = $blankInfos ? array_column($blankInfos, null, 'bid') : [];
        $guideInfos = $guideIds ? mGuide::getGuideByIdsALl($guideIds) : [];

        $list = [];
        foreach ($objList as $objType => $objIds) {
            foreach ($objIds as $objId) {
                switch ($objType) {
                    case mObjRelateWiki::OBJ_TYPE_NOTE:
                        $noteInfo = $noteInfos[$objId] ?? [];
                        if ($noteInfo) {
                            $uid = $noteInfo['uid'];
                            $userInfo = $userList[$uid] ?? [];
                            if (\Doraemon\service\Photos::SHOW_TYPE_VIDEO == $noteInfo['show_type']) {
                                $picUrl = $videos[$noteInfo['video_id']] ? $videos[$noteInfo['video_id']]['thumb_pic_url'] : '';
                            } else {
                                $picUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $noteInfo['pic_id'], ImgUrl::IMAGE_SIZE_1280);
                            }
                            $list[] = [
                                'uid' => $uid,
                                'nick' => $userInfo['nick'] ?? '',
                                'type' => $userInfo ? Member::$typeDesc[$userInfo['type']] : '',
                                'obj_id' => $objId,
                                'obj_type' => BlockType::TYPE_NAME_MAP[BlockType::TYPE_PHOTO],
                                'title' => $noteInfo['title'] ?? '',
                                //'remark' => $noteInfo['remark'] ?? '',
                                'pic_url' => $picUrl ? '<img src="' . $picUrl . '" style="width:100px;height:100px;" >' : '',
                                'addtime' => date('Y-m-d', $noteInfo['addtime']),
                                'score' => $noteInfo['admin_score'],
                            ];
                        }
                        break;
                    case mObjRelateWiki::OBJ_TYPE_BLANK:
                        $blankInfo = $blankInfos[$objId] ?? [];
                        if ($blankInfo) {
                            $uid = $blankInfo['uid'];
                            $userInfo = $userList[$uid] ?? [];
                            $picUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $blankInfo['cover_pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                            $list[] = [
                                'uid' => $uid,
                                'nick' => $userInfo['nick'] ?? '',
                                'type' => $userInfo ? Member::$typeDesc[$userInfo['type']] : '',
                                'obj_id' => $objId,
                                'obj_type' => BlockType::TYPE_NAME_MAP[BlockType::TYPE_BLANK],
                                'title' => $blankInfo['title'],
                                //'remark' => $blankInfo['remark'],
                                'pic_url' => $picUrl ? '<img src="' . $picUrl . '" style="width:100px;height:100px;" >' : '',
                                'addtime' => date('Y-m-d', $blankInfo['addtime']),
                                'score' => $blankInfo['admin_score'],
                            ];
                        }
                        break;
                    case mObjRelateWiki::OBJ_TYPE_ARTICLE:
                        $articleInfo = $articleInfos[$objId] ?? [];
                        if ($articleInfo) {
                            $uid = $articleInfo['uid'];
                            $userInfo = $userList[$uid] ?? [];
                            $picUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $articleInfo['cover_pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                            $list[] = [
                                'uid' => $uid,
                                'nick' => $userInfo['nick'] ?? '',
                                'type' => $userInfo ? Member::$typeDesc[$userInfo['type']] : '',
                                'obj_id' => $objId,
                                'obj_type' => BlockType::TYPE_NAME_MAP[BlockType::TYPE_ARTICLE],
                                'title' => $articleInfo['title'],
                                //'remark' => $articleInfo['remark'],
                                'pic_url' => $picUrl ? '<img src="' . $picUrl . '" style="width:100px;height:100px;" >' : '',
                                'addtime' => date('Y-m-d', $articleInfo['addtime']),
                                'score' => $articleInfo['admin_score'],
                            ];
                        }
                        break;
                    case mObjRelateWiki::OBJ_TYPE_GUIDE:
                        $guideInfo = $guideInfos[$objId] ?? [];
                        if ($guideInfo) {
                            $uid = $guideInfo['uid'];
                            $userInfo = $userList[$uid] ?? [];
                            $picUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $guideInfo['cover_pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                            $list[] = [
                                'uid' => $uid,
                                'nick' => $userInfo['nick'] ?? '',
                                'type' => $userInfo ? Member::$typeDesc[$userInfo['type']] : '',
                                'obj_id' => $objId,
                                'obj_type' => BlockType::TYPE_NAME_MAP[BlockType::TYPE_GUIDE],
                                'title' => $guideInfo['title'],
                                //'remark' => $guideInfo['remark'],
                                'pic_url' => $picUrl ? '<img src="' . $picUrl . '" style="width:100px;height:100px;" >' : '',
                                'addtime' => date('Y-m-d', $articleInfo['addtime']),
                                'score' => '无',
                            ];
                        }
                        break;
                }
            }
        }
        $result['count'] = $count;
        $result['table'] = [
            'header' => ['UID', '昵称', '身份', '内容ID', '类型', '标题', '图片', '发布时间', '打分'],
            'list' => $list
        ];
        return $result;
    }
}
